package cn.tedu.ivos01.user.service.impl;


import cn.tedu.ivos01.base.exception.ServiceException;
import cn.tedu.ivos01.base.response.StatusCode;
import cn.tedu.ivos01.user.mapper.UserMapper;
import cn.tedu.ivos01.user.pojo.dto.UserLoginParam;
import cn.tedu.ivos01.user.pojo.dto.UserQuery;
import cn.tedu.ivos01.user.pojo.dto.UserSaveParam;
import cn.tedu.ivos01.user.pojo.entity.User;
import cn.tedu.ivos01.user.pojo.vo.UserVO;
import cn.tedu.ivos01.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    // 用户登录功能接口实现
    @Override
    public UserVO login(UserLoginParam userLoginParam) {
        log.debug("用户登录参数: userLoginParam:{}",userLoginParam);
        UserVO userVO = userMapper.selectByUsername(userLoginParam.getUsername());
        if (userVO ==null){
            throw  new ServiceException(StatusCode.USERNAME_ERROR);
        }
        if (!userVO.getPassword().equals(userLoginParam.getPassword())){
            throw new ServiceException(StatusCode.PASSWORD_ERROR);
        }
        return userVO;
    }

    //保存用户功能
    @Override
    public void saveUser(UserSaveParam userSaveParam) {
        User user = new User();
        BeanUtils.copyProperties(userSaveParam,user);
        if (user.getId()==null){
            //如果前端传递的数据不包含Id,则进行新增用户的操作
            if (userMapper.selectByUsername(user.getUsername())!=null){
                throw new ServiceException(StatusCode.USERNAME_ERROR);
            }
            //员工数据不是员工自己注册的,所以需要预设一个新的出事密码
            user.setPassword("123456");
            user.setCreateTime(new Date());
            userMapper.insert(user);
        }else {
            //如果传入的包含Id.则进行更新操作
            user.setUpdateTime(new Date());
            userMapper.update(user);
        }
    }

    @Override
    public List<UserVO> selectUser(UserQuery userQuery) {
        List<UserVO> list = userMapper.selectUser(userQuery);
        return list;
    }

//    重置密码功能
    @Override
    public void resetPassword(Long userId) {
        User user = new User();
        user.setId(userId);
        user.setPassword("admin");
        userMapper.update(user);
    }

    //删除用户功能
    @Override
    public void deleteUser(Long userId) {
        userMapper.deleteById(userId);
    }

}
